// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

import modules from "./modules/index.js";
import getters from "./getters.js";

/**
 * 微信小程序状态管理类
 * 替代Vuex，提供类似的状态管理功能
 */
class Store {
  constructor() {
    this.state = {};
    this.getters = {};
    this.mutations = {};
    this.actions = {};
    this.modules = {};
    this.subscribers = [];
    
    this.initModules(modules);
    this.initGetters(getters);
  }

  /**
   * 初始化模块
   * @param {Object} modules 模块配置
   */
  initModules(modules) {
    console.log('initModules', modules);
    Object.keys(modules).forEach(moduleName => {
      console.log('moduleName',moduleName)
      const module = modules[moduleName];
      this.modules[moduleName] = module;
      
      // 初始化模块状态
      if (module.state) {
        this.state[moduleName] = typeof module.state === 'function' 
          ? module.state() 
          : { ...module.state };
      }
      
      // 注册mutations
      if (module.mutations) {
        Object.keys(module.mutations).forEach(mutationName => {
          const fullName = `${moduleName}/${mutationName}`;
          this.mutations[fullName] = module.mutations[mutationName];
        });
      }
      
      // 注册actions
      if (module.actions) {
        Object.keys(module.actions).forEach(actionName => {
          const fullName = `${moduleName}/${actionName}`;
          this.actions[fullName] = module.actions[actionName];
        });
      }
    });
  }

  /**
   * 初始化getters
   * @param {Object} gettersConfig getters配置
   */
  initGetters(gettersConfig) {
    Object.keys(gettersConfig).forEach(getterName => {
      this.getters[getterName] = gettersConfig[getterName];
    });
  }

  /**
   * 提交mutation
   * @param {String} type mutation类型
   * @param {*} payload 载荷
   */
  commit(type, payload) {
    // 只在开发环境下输出详细日志
    // 小程序环境不支持 process.env，使用其他方式判断开发环境
    // if (process.env.NODE_ENV === 'development') {
    //   console.log('commit this.mutations',this.mutations)
    // }
    // 方案3：使用配置开关
    // if (getApp().globalData.debug) {
    //   console.log('commit this.mutations', this.mutations);
    // }
    const mutation = this.mutations[type];
    if (!mutation) {
      console.warn(`[Store] Unknown mutation type: ${type}`);
      return;
    }

    // 解析模块名和mutation名
    const [moduleName, mutationName] = type.split('/');
    const moduleState = this.state[moduleName];
    
    if (!moduleState) {
      console.warn(`[Store] Unknown module: ${moduleName}`);
      return;
    }

    console.log('moduleName = '+moduleName);
    console.log('type='+ type);
    console.log('payload='+payload);
    console.log('moduleState'+moduleState);

    // 执行mutation
    mutation(moduleState, payload);
    
    // 通知订阅者
    this.notifySubscribers(type, payload);
  }

  /**
   * 分发action
   * @param {String} type action类型
   * @param {*} payload 载荷
   */
  dispatch(type, payload) {
    const action = this.actions[type];
    if (!action) {
      console.warn(`[Store] Unknown action type: ${type}`);
      return Promise.reject(new Error(`Unknown action type: ${type}`));
    }

    // 解析模块名和action名
    const [moduleName] = type.split('/');
    const moduleState = this.state[moduleName];
    
    if (!moduleState) {
      console.warn(`[Store] Unknown module: ${moduleName}`);
      return Promise.reject(new Error(`Unknown module: ${moduleName}`));
    }

    // 创建context对象
    const context = {
      state: moduleState,
      rootState: this.state,
      commit: (mutationType, mutationPayload) => {
        this.commit(mutationType, mutationPayload);
      },
      dispatch: (actionType, actionPayload) => {
        return this.dispatch(actionType, actionPayload);
      }
    };

    // 执行action
    return action(context, payload);
  }

  /**
   * 获取状态
   * @param {String} path 状态路径，如 'app/token' 或 'app'
   */
  getState(path) {
    if (!path) return this.state;
    
    const parts = path.split('/');
    let result = this.state;
    
    for (const part of parts) {
      if (result && typeof result === 'object' && part in result) {
        result = result[part];
      } else {
        return undefined;
      }
    }
    
    return result;
  }

  /**
   * 获取getter值
   * @param {String} getterName getter名称
   */
  getGetter(getterName) {
    const getter = this.getters[getterName];
    if (!getter) {
      console.warn(`[Store] Unknown getter: ${getterName}`);
      return undefined;
    }
    
    return getter(this.state);
  }

  /**
   * 订阅状态变化
   * @param {Function} callback 回调函数
   */
  subscribe(callback) {
    this.subscribers.push(callback);
    
    // 返回取消订阅函数
    return () => {
      const index = this.subscribers.indexOf(callback);
      if (index > -1) {
        this.subscribers.splice(index, 1);
      }
    };
  }

  /**
   * 通知订阅者
   * @param {String} type mutation类型
   * @param {*} payload 载荷
   */
  notifySubscribers(type, payload) {
    this.subscribers.forEach(callback => {
      try {
        callback({ type, payload }, this.state);
      } catch (error) {
        console.error('[Store] Error in subscriber callback:', error);
      }
    });
  }

  /**
   * 替换状态（用于调试）
   * @param {Object} newState 新状态
   */
  replaceState(newState) {
    this.state = newState;
  }
}

// 创建全局store实例
const store = new Store();

export default store;